<?php

namespace app\admin\controller;

use think\Db;
use app\common\controller\Backend;
use app\admin\model\BydDesignerArea;
/**
 * 楼盘信息
 *
 * @icon fa fa-circle-o
 */
class SoleBuilding extends Backend
{
    
    /**
     * SoleBuilding模型对象
     * @var \app\admin\model\SoleBuilding
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\SoleBuilding;

    }

    public function import()
    {
        parent::import();
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

     /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {

//                $name=$params['title'];
//                $bz=$params['standard'];
//                $adedress=$params['address'];
//                $time=$params['trun_time'];
//                $huxin=$params['house_type'].$params['house_area'];
//                $array=explode(",", $params['house_imgs']);;
//                foreach ($array as $v){
//                    $image[]='https://bao.scwushen.com/'.$v;
//                }
////                print_r($images);die;
////                $image=explode(',',$images);
////                print_r($params['house_imgs']);die;
//                $path= APP_PATH.'api/view/demo/abc.html';
//                $opempath=fopen($path,'a+');
//                $arr=fread($opempath,filesize($path));
//               // $arr=str_replace('{$name}',$name,$arr);
//                $arr=str_replace('{$name}','乙方姓名',$arr);
//                $arr=str_replace('{$sheng}','xxx',$arr);
//                $arr=str_replace('{$shi}','xxx',$arr);
//                $arr=str_replace('{$qu}','xxx',$arr);
//                $arr=str_replace('{$lp}','xxx',$arr);
//                $imagestring='';
//                foreach ($image as $v){
//                    $imagestring.='<img src='.$v.'>';
//                }
//                $arr=str_replace('{$image}',$imagestring,$arr);
//                $add=new \app\admin\model\BydAgreement();
//                $add->data([
//                    'name'=>$params['title'].'(楼盘协议)',
//                    'content'=>$arr,
//                    'state'=>13
//
//                ]);
//                $add->save();

                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                
                if(intval($params['area_id']) <= 0) $this->error(__('请选择楼盘所属区域'));
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    // print_r($params);
                    // die;
                    $params['create_time'] = time();
                    $params['update_time'] = time();
                    $result = $this->model->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    if($add){
                        $addss=\app\admin\model\SoleBuilding::where('id',$this->model->id)->update(['aid'=>$add->id]);
                    }
                    $adds=\app\admin\model\SoleBuilding::where('id',$this->model->id)->update(['content'=>$arr]);
                    $findd=BydDesignerArea::where('id',$params['area_id'])->setInc('num');
                    $find=BydDesignerArea::where('id',$params['area_id'])->find();
                    $findp=BydDesignerArea::where('id',$find['pid'])->setInc('num');
                    $findss=BydDesignerArea::where('id',$find['pid'])->find();
                    $findpp=BydDesignerArea::where('id',$findss['pid'])->setInc('num');
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }



     
    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
//        print_r($adminIds);
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $params['update_time'] = time();
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty'));
        }
        
        $row =  $row->toArray();
        $res = BydDesignerArea::get($row['area_id']);
     
        if(!empty($res) && $res['level'] = 2)
        {
            $city = BydDesignerArea::where('id','=',$res->pid)->find();
            $row['city_id'] = $city->id;
            $row['province_id'] = $city->pid;
         
        }
        else
        {
            $row['province_id'] = 0;
            $row['city_id'] = 0;
        }
        
        
        
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }
    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            $find=\app\admin\model\SoleBuilding::where('id','in',$ids)->select();
            foreach ($find as $v){
                $de1=BydDesignerArea::where('id',$v['area_id'])->setDec('num');
                $find1=BydDesignerArea::find($v['area_id']);
                $de2=BydDesignerArea::where('id',$find1['pid'])->setDec('num');
                $find2=BydDesignerArea::find($find1['pid']);
                $de3=BydDesignerArea::where('id',$find2['pid'])->setDec('num');
            }
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();

            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    $count += $v->delete();
                }
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }
    /**
     * 真实删除
     */
    public function destroy($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        $pk = $this->model->getPk();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        if ($ids) {
            $this->model->where($pk, 'in', $ids);
            $find=\app\admin\model\SoleBuilding::where('id','in',$ids)->select();
            foreach ($find as $v){
                $de1=BydDesignerArea::where('id',$v['area_id'])->setDec('num');
                $find1=BydDesignerArea::find($v['area_id']);
                $de2=BydDesignerArea::where('id',$find1['pid'])->setDec('num');
                $find2=BydDesignerArea::find($find1['pid']);
                $de3=BydDesignerArea::where('id',$find2['pid'])->setDec('num');

            }
        }
        $count = 0;
        Db::startTrans();
        try {
            $list = $this->model->onlyTrashed()->select();
            foreach ($list as $k => $v) {
                $count += $v->delete(true);
            }
            Db::commit();
        } catch (PDOException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        } else {
            $this->error(__('No rows were deleted'));
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }
}
